package com.sgq.utils;

import com.sgq.entity.Department;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author: 83778
 * @date: 2024-09-24 9:01
 * @desc:
 */
public class DepartmentTree {


    public static List<Department> makeDepartmentTree(List<Department> departmentList , Long pid){

        List<Department> departments = new ArrayList<>();

        Optional.ofNullable(departmentList)
                .orElse(new ArrayList<Department>())
                .stream()
                .filter(item -> item != null && item.getPid() == pid)
                .sorted(Comparator.comparing(Department::getOrderNum))
                .forEach(item ->{
                    //创建一个新的部门对象
                    Department department = new Department();
                    //把满足条件的对象复制到新的部门对象中
                    BeanUtils.copyProperties(item,department);
                    //获取部门的id => 把它作为父id
                    Long id = department.getId();
                    List<Department> children = makeDepartmentTree(departmentList, id);
                    department.setChildren(children);
                    departments.add(department);
                });

        return departments;
    }
}
